﻿
using System;
using System.Threading.Tasks;
using Windows.Security.Authorization.AppCapabilityAccess;
using Xiaowei.Diagnostics;

namespace Xiaowei.Services
{
    public delegate void MicrophoneAvailableHandler(bool availability);
    public delegate void MicrophoneActivateHandler(bool activated);
    public static class Microphone
    {
        public static event MicrophoneAvailableHandler AvailableChanged;
        private static bool? isAvailable;
        public static bool IsAvailable => AppCapability.CheckAccess() == AppCapabilityAccessStatus.Allowed;

        public static event MicrophoneActivateHandler Activated;
        private static bool isActivated = true;
        public static bool IsActivated 
        {
            get { return isActivated; }
            set {
                isActivated = value;
                Activated?.Invoke(value);
            } 
        }

        private static AppCapability appCapability = null;
        private static AppCapability AppCapability
        {
            get
            {
                if (appCapability == null)
                {
                    appCapability= AppCapability.Create("microphone");
                }
                return appCapability;
            }
        }
        public static void Init()
        {
            AppCapability.AccessChanged += (capability, args) =>
            {
                AvailableChanged?.Invoke(capability.CheckAccess() == AppCapabilityAccessStatus.Allowed);
                var isAvailable = capability.CheckAccess() == AppCapabilityAccessStatus.Allowed;
                if (isAvailable)
                {
                    LEDStateManager.RemoveAttachState(LEDStateManager.AttachStateEnum.error2);
                }
                else
                {
                    LEDStateManager.SetAttachState(LEDStateManager.AttachStateEnum.error2);
                }
            };

            Debug.WriteLine($"Microphone.Init, IsAvailable={AppCapability.CheckAccess() == AppCapabilityAccessStatus.Allowed}");
            var available = AppCapability.CheckAccess() == AppCapabilityAccessStatus.Allowed;
            if (available)
            {
                LEDStateManager.RemoveAttachState(LEDStateManager.AttachStateEnum.error2);
            }
            else
            {
                LEDStateManager.SetAttachState(LEDStateManager.AttachStateEnum.error2);
            }
            //ConnectionManager.AddHandler("MicrophoneState", (v) =>
            //{
            //    if (v["Active"] is bool b)
            //    {
            //        IsActivated = b;
            //    }
            //});

            Debug.WriteLine($"Microphone.IsAvailable:{IsAvailable}");
        }
    }
}
